import { useFrame } from "@react-three/fiber";
import gsap from "gsap";
import { useState, useEffect, useRef } from "react";
import * as THREE from "three";

/**
 * 创建一个地球
 * @returns
 */
export function Map() {
  const torusGeometryRef = useRef<THREE.TorusGeometry>(null);
  const [radius, setRadius] = useState<number>(45);
  const earthGroup = useRef<THREE.Group>(null);
  const [texture, setTexture] = useState<THREE.Texture | undefined>();
  const getTexture = () => {
    const textureLoader = new THREE.TextureLoader();
    const texture = textureLoader.load("/imgs/map.jpg");
    setTexture(texture);
  };
  const animate = () => {
    const state = {
      rotationY:0
    }
    gsap.fromTo(
      state,
      { rotationY: 0 },
      {
        rotationY: Math.PI / 180 * 1,
        duration: 1000,
        repeat: -1,
        onUpdate: function () {
          earthGroup.current?.rotateY(state.rotationY);
          console.log("earthGroup.current.rotationY", earthGroup.current);
        },
      }
    );
  };
  useEffect(() => {
    getTexture();
    torusGeometryRef.current?.rotateX(Math.PI / 2);
    // animate();
    console.log("texture", texture);
  }, []);

  return (
    <>
      <group ref={earthGroup}>
        <mesh>
          <sphereGeometry args={[30, 32, 66]} />
          <meshBasicMaterial
            map={texture}
            side={THREE.DoubleSide}
            transparent={true}
            // color={new THREE.Color("#d61b1b")}
          />
        </mesh>
        <mesh>
          <torusGeometry
            ref={torusGeometryRef}
            args={[45, 1, 16, 100]}
          ></torusGeometry>
          <meshStandardMaterial color={new THREE.Color("#888080")} />
        </mesh>
      </group>
    </>
  );
}
